#include "utils.h"
#include "BMP.h"
#include "GIFDecoder.h"

using namespace std;

int main(int argc, char *argv[]) {
	
	// Verifico che ci sia un parametro
	if (argc!=3) {
		cout << endl << endl << "GIF to BMP converter. Syntax: gif2bmp <source gif filename> <destination bmp filename>" << endl<<endl<<"Usage: Convert <source filename> in <destination filename> "<<endl<<endl;
		return -1;
	}
	bool exitVal;
	if ( strcmp( argv[1], argv[2] ) == 0 ){
		cout << endl << endl << "User error: The <source filename> and <destination filename> must be different";
		cout << endl << endl << "GIF to BMP converter. Syntax: gif2bmp <source gif filename> <destination bmp filename>" << endl<<endl<<"Usage: Convert <source filename> in <destination filename> "<<endl<<endl;		
		return -1;
	}
	else{
		exitVal = false;		
		/***************************** GIF DECODER *****************************/
		cout << "GIF decoder started (standard 87a)" << endl;
		string fileGIF = argv[1];
		fstream fin(fileGIF.c_str(), ios::in | ios::binary);		
		if (!fin){
			cout << "Cannot open the file: " << fileGIF << endl;
			return -1;
		}
		// Read GIF file
		GIFFile fGIF;
		if (!fGIF.readGIFFile(fin)){
			cout << "Cannot read GIF file" << endl;
			fin.close();
			return -1;
		}	
		// Print GIF file (file header, image header)
		fGIF.printGIFFile();							
		fin.close();									
		cout << endl << "GIF decoder terminated." << endl;

		cout<< endl<<endl<<endl;

		/*****************************  BMP ENCODER *****************************/
		cout << endl << "BMP encoder started" << endl;
		
		// set target filename
		string fileBMP = argv[2];;
		fstream fout(fileBMP.c_str(), ios::out | ios::binary);	
		
		// Creates a BMPFile structure
		BMPFile fBMP;

		// Getting original GIF file information to construct BMP target file
		WORD ImageWidth = fGIF.getImageWidth();				// Image Width
		WORD ImageHeight = fGIF.getImageHeight();			// Image Height
		ColorPaletteEntry *ColorMap = fGIF.getColorMap();	// Color Palette
		BYTE *ImageIndices = fGIF.getImageIndices();		// Pixel Indices

		// buliding BMPFile with loading info
		if (!fBMP.buildBMPFile(fout, ImageWidth, ImageHeight, ColorMap, ImageIndices)){
			cout << "BMP file build error!" << endl;
			fout.close();
		}		
		fout.close();
		
		fBMP.printBITMAPFILEHEADER();
		fBMP.printBITMAPINFOHEADER();
		fBMP.printColorPalette();
		fBMP.printBitmapData();
		cout << endl << "BMP encoder terminated." << endl;

		if (exitVal == true){
			cout<<"Conversion Failure"<<endl<<"Press any key to continue...";
			getch();
			return 1;
		}
	}

	cout<<endl<<"Press any key to continue..";
	getch();
	cout<<endl;
	return 0;
}